<template>
  <div>
    <div>
      <el-tag v-for="(item, index) in value" :key="index" :closable="!disabled" @close="handleRemove(index)">
        {{item['deptName'] && item['deptName']}}
        {{item['deptName'] && (item['positionName'] || item['userName']) ? ' / ' : ''}}
        {{item['positionName'] && item['positionName']}}
        {{(item['deptName']|| item['positionName']) && item['userName'] ? ' / ' : ''}}
        {{item['userName'] && item['userName']}}
      </el-tag>
      <el-button  v-if="!disabled" type="primary" size="mini" @click="handleAdd" :style="{ marginLeft: '10px'}">
        {{multiple ? '添加' : '选择'}}
      </el-button>
    </div>
    <dept-position-man ref="deptPosUser" :mode="mode" @handleSelected="handleDeptPosUserSelected" />
  </div>
</template>

<script>
import DeptPositionMan from '@/components/DeptPositionMan'

export default {
  name: 'DeptPositionUser',
  components: { DeptPositionMan },
  props: {
    mode: { // standard标准模式（必须选择部门-岗位-人员的模式），free任意模式（可以任意选择那几级）
      type: String,
      default: 'standard'
    },
    // 禁选
    disabled: {
      type: Boolean,
      default: false
    },
    // 多选框
    multiple: {
      type: Boolean,
      default: false
    },
    // 选择值
    selectValue: {
      type: Array,
      default: null
    }
  },
  watch: {
    selectValue: {
      handler(n, o) {
        this.value = n
      },
      deep: true,
      immediate: true
    },
    // value: {
    //   handler(n, o) {
    //     this.$emit('valueChange', n)
    //   },
    //   deep: true,
    //   immediate: true
    // }
  },
  created() {
    if (this.selectValue) {
      this.value = this.selectValue
    }
  },
  data() {
    return {
      value: undefined
    }
  },
  methods: {
    handleAdd() { // 点击选择部门岗位人员
      this.$refs.deptPosUser.show()
    },
    handleDeptPosUserSelected(selection) { // 选择部门岗位人员回调
      this.value = this.value || []
      if (!this.multiple) {
        this.value = []
      }
      const item = JSON.parse(JSON.stringify(selection))
      this.value.push(item)
      this.$emit('valueChange', this.value)
    },
    handleRemove(index) { // 移除已选择的部门岗位人员
      this.value.splice(index, 1)
      this.$emit('valueChange', this.value)
    }
  }
}
</script>